package web.blogsphere.controller;

// 客户端是前端 服务端是后端

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import web.blogsphere.constant.Constants;
import web.blogsphere.model.Result;
import web.blogsphere.model.UserInfo;
import web.blogsphere.service.UserService;
import web.blogsphere.utils.JwtUtils;
import web.blogsphere.utils.SecurityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author ZJX
 * @Date 2024/9/4 13:30
 * @Version 1.0
 */
@RequestMapping("/user")
@RestController
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName,String password){
//        1. 参数校验是否合法
//        2. 校验密码是否正确
//        正确 -> 返回 token , 错误 提醒错误
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("账号或密码不能为空");
        }

//        从数据库中查找用户
        UserInfo userInfo = userService.selectByName(userName);

        if (userInfo == null){
            return Result.fail("用户不存在!");
        }

//        密码错误
        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            log.error("密码错误");
            return Result.fail("密码错误");
        }

//        此处 说明 密码正确
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        System.out.println(token);
        return Result.success(token);
    }

//    获取 当前用户信息 通过 token 中获取
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        log.info("获取用户信息....");
        //获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        //从token中获取登录用户ID
        Integer userId = JwtUtils.getIdByToken(token);
        if (userId == null){
            //用户未登录
            return null;
        }
        UserInfo userInfo = userService.selectById(userId);
        return userInfo;
    }

//    通过 博客 id 获取 用户信息
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){

        if (blogId <= 0){
            return null;
        }
        UserInfo userInfo = userService.getAuthorInfo(blogId);

        if (userInfo == null){
            return null;
        }

        return userInfo;
    }
}
